package drds.global_transaction.resource_manager.model;

import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.alibaba.fastjson.annotation.JSONField;

import lombok.Getter;
import lombok.NonNull;
import lombok.Setter;

public class Image
{

	@Setter
	@Getter
	@JSONField(serialize = false)
	private TableMetaData tableMetaData;
	@Setter
	@Getter
	private String tableName;
	@Setter
	@Getter
	private List<Record> recordList = new ArrayList<Record>();

	public Image()
	{

	}

	public Image(TableMetaData tableMetaData)
	{
		setTableMetaData(tableMetaData);
	}

	public static Image empty(TableMetaData tableMetaData)
	{
		return new Image(tableMetaData)
		{
			@Override
			public int size()
			{
				return 0;
			}

			@Override
			public List<Column> getPrimaryKeyColumnList()
			{
				return new ArrayList<>();
			}

			@Override
			public void add(Record record)
			{
				throw new UnsupportedOperationException("xxx");
			}

			@Override
			public TableMetaData getTableMetaData()
			{
				throw new UnsupportedOperationException("xxx");
			}
		};
	}

	public static Image buildImage(TableMetaData tableMetaData, ResultSet resultSet) throws SQLException
	{
		Image image = new Image(tableMetaData);
		ResultSetMetaData resultSetMetaData = resultSet.getMetaData();
		int columnCount = resultSetMetaData.getColumnCount();
		while (resultSet.next())
		{
			List<Column> columnList = new ArrayList<>(columnCount);
			for (int i = 1; i <= columnCount; i++)
			{
				String columnName = resultSetMetaData.getColumnName(i).toLowerCase();// 小写
				ColumnMetaData columnMeta = tableMetaData.getColumnMeta(columnName);
				Column column = new Column();
				column.setName(columnMeta.getColumnName());
				if (tableMetaData.getFirstPrimaryKeyColumnName().equals(column.getName()))
				{
					column.setKeyType(KeyType.primary_key);
				}
				column.setType(columnMeta.getDataType());
				column.setValue(resultSet.getObject(i));
				columnList.add(column);
			}
			Record record = new Record();
			record.setColumnList(columnList);
			image.add(record);
		}
		return image;
	}

	public void setTableMetaData(@NonNull TableMetaData tableMetaData)
	{
		this.tableMetaData = tableMetaData;
		this.tableName = tableMetaData.getTableName();
	}

	public List<Column> getPrimaryKeyColumnList()
	{
		final String firstPrimaryKeyColumnName = getTableMetaData().getFirstPrimaryKeyColumnName();
		return new ArrayList<Column>()
		{
			private static final long serialVersionUID = 1L;

			{
				for (Record record : recordList)
				{
					List<Column> columns = record.getColumnList();
					for (Column column : columns)
					{
						if (column.getName().equalsIgnoreCase(firstPrimaryKeyColumnName))
						{
							add(column);
							break;
						}
					}
				}
			}
		};
	}
	//

	public void add(Record record)
	{
		recordList.add(record);
	}

	public int size()
	{
		return recordList.size();
	}

}
